<template>
  <div>
    <el-row gutter="10" style="margin-bottom: 40px">
      <el-col :span="12">
        <el-card style="color: #409EFF;">
          <div><i class="el-icon-user-solid"/> 用户总数</div>
          <div style="padding:10px 0;text-align: center;font-weight: bold;font-size: larger">{{ countUser }}</div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card style="color: #67C23A">
          <div><i class="el-icon-link"/> 当前在线人数</div>
          <div style="padding:10px 0;text-align: center;font-weight: bold;font-size: larger">{{ countOnlineUser }}</div>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <div id="main" style="width: 500px;height: 400px;margin-left: 50px"></div>
      </el-col>
      <el-col :span="12">
        <div id="pie" style="width: 500px;height: 400px;margin-left: 50px"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
let socket;
let onlineUsers = [];
let countOnlineUser = 0;
let countUser = 0;
import * as echarts from 'echarts';

export default {
  name: "Home",
  data() {
    return {
      countUser: 0,
      countOnlineUser: 0
    }
  },
  //页面渲染之后
  mounted() {
    //总人数
    this.request.get("/user/count").then(res => {
      this.countUser = res.data
      countUser = res.data
      //sock初始化
      this.socketInit()
    })

    //折线图
    var chartDom = document.getElementById('main');
    var myChart = echarts.init(chartDom);
    var option = {
      title: {
        text: '一周内注册人数',
        subtext: '趋势图',
        bottom: 'bottom',
        left: 'center',
      },
      xAxis: {
        type: 'category',
        data: ['第一天', '第二天', '第三天', '第四天', '第五天', '第六天', '第七天（今天）']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [],
          type: 'line'
        }
      ]
    };
    this.request.get("/echarts/example").then(res => {
      console.log("=====" + JSON.stringify(res.data))
      if (res.code != '200') {
        this.$message.error("数据请求失败，请刷新页面或联系管理员")
        return false
      }
      option.series[0].data = res.data
      option && myChart.setOption(option);
    })
    setTimeout(()=>{
      this.$alert('<br/><i class="el-icon-warning-outline"/> 由于服务器带宽问题，头像暂时不能正常显示，但请放心，您精心仔细挑选的头像会妥善保存在服务器中，在不久的将来即可正常显示',
          '注意',
          {
            confirmButtonText: '我知道了',
            center: true,
            showClose: false,
            dangerouslyUseHTMLString: true,
          });
    },1000)
  },
  methods: {
    //构建饼图
    pieCreat() {
      //饼图
      let t = countUser - countOnlineUser
      console.log(countOnlineUser)
      let udata = [{value: t, name: "离线人数"}, {value: countOnlineUser, name: "在线人数"}];
      var pieChartDom = document.getElementById('pie');
      var pieMyChart = echarts.init(pieChartDom);
      var pieOption = {
        title: {
          text: '当前用户分布',
          bottom: 'bottom',
          left: 'center',
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            name: '用户分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '40',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: udata
          }
        ]
      };
      pieOption && pieMyChart.setOption(pieOption);
    },
    // socket初始化
    socketInit() {
      onlineUsers = []
      let _this = this;
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://www.asiawu.cn:9090/onlinechat/" + JSON.parse(localStorage.getItem("user")).username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        socket.onmessage = function (msg) {
          // console.log("收到数据====" + msg.data)
          //显示在线用户
          for (let i = 0; i < JSON.parse(msg.data).users.length; i++) {
            onlineUsers.push(JSON.parse(msg.data).users[i].username)
          }
          //阻止越刷新在线用户越多的bug
          if (_this.countOnlineUser == 0) {
            _this.countOnlineUser = onlineUsers.length
            countOnlineUser = onlineUsers.length
            _this.pieCreat()
          }
        }
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
      }
    }
  }
}
</script>
<style scoped>

</style>